<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>地图展示</title>
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            height: 100vh;
            height: 100dvh; /* 动态视口高度，适应地址栏变化 */
            overflow: hidden;
            position: fixed;
            width: 100%;
            top: 0;
            left: 0;
        }
        .header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 2000;
            margin-bottom: 0;
            padding: 8px 12px;
            background-color: #f0f0f0;
            border-radius: 0;
            min-height: 60px;
            box-sizing: border-box;
        }
        .room-input {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-bottom: 5px;
            flex-wrap: wrap;
        }
        .room-input input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .room-input button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .room-input button:hover {
            background-color: #0056b3;
        }
        .room-input button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .auto-refresh-group {
            display: flex;
            gap: 5px;
            align-items: center;
        }
        .refresh-btn {
            padding: 6px 12px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s;
        }
        .refresh-btn:hover {
            background-color: #218838;
            transform: translateY(-1px);
        }
        .refresh-btn.active {
            background-color: #ffc107;
            color: #212529;
            box-shadow: 0 2px 8px rgba(255, 193, 7, 0.3);
        }
        .refresh-btn.stop-btn {
            background-color: #dc3545;
        }
        .refresh-btn.stop-btn:hover {
            background-color: #c82333;
        }
        .content {
            position: relative;
            height: calc(100vh - 85px);
            height: calc(100dvh - 85px); /* 动态视口高度减去header高度 */
            min-height: 400px;
            margin-top: 85px; /* 为header留出空间，增加5px避免按钮遮挡 */
        }
        .sidebar {
            position: absolute;
            top: 15px;
            left: 5px;
            width: 120px;
            max-height: calc(100vh - 80px);
            background-color: transparent;
            backdrop-filter: none;
            border-radius: 0;
            padding: 6px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: none;
            border: none;
        }
        .sidebar h4 {
            margin: 0 0 4px 0;
            color: #333;
            font-size: 14px;
            text-align: left;
            padding-bottom: 2px;
            border-bottom: 1px solid rgba(0,0,0,0.1);
        }
        .show-all-btn {
            width: 100%;
            padding: 6px 8px;
            margin-bottom: 8px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            font-weight: bold;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .show-all-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
        .show-all-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .show-all-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .person-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .person-item {
            padding: 4px 6px;
            margin-bottom: 4px;
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 4px;
            cursor: pointer;
            border: 1px solid transparent;
            transition: all 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .person-item:hover {
            background-color: rgba(227, 242, 253, 0.95);
            border-color: #2196f3;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(33, 150, 243, 0.2);
        }
        .person-item.active {
            background-color: rgba(187, 222, 251, 0.95);
            border-color: #1976d2;
            box-shadow: 0 2px 12px rgba(25, 118, 210, 0.3);
        }
        .person-item.recent {
            background-color: rgba(200, 255, 200, 0.9) !important;
            border-color: #4caf50;
            box-shadow: 0 2px 8px rgba(76, 175, 80, 0.2);
        }
        .person-item.recent:hover {
            background-color: rgba(180, 255, 180, 0.95) !important;
            border-color: #388e3c;
            box-shadow: 0 3px 12px rgba(56, 142, 60, 0.3);
        }
        .person-item.recent.active {
            background-color: rgba(165, 245, 165, 0.95) !important;
            border-color: #2e7d32;
            box-shadow: 0 3px 15px rgba(46, 125, 50, 0.4);
        }
        .person-name {
            font-weight: bold;
            color: #333;
            font-size: 14px;
        }
        .person-time {
            font-size: 11px;
            color: #666;
            white-space: nowrap;
        }
        #map {
            width: 100%;
            height: 100%;
            border-radius: 0;
            box-shadow: none;
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 20px;
        }
        .error {
            color: #dc3545;
            background-color: #f8d7da;
            padding: 10px;
            border-radius: 4px;
            margin-top: 10px;
        }

                .success {
            color: #155724;
            background-color: #d4edda;
            padding: 6px 10px;
            border-radius: 4px;
            margin-top: 5px;
            font-size: 12px;
            border-left: 3px solid #28a745;
            position: relative;
            z-index: 10;
        }

        /* 自定义标记样式 */
        .custom-marker {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            border: 3px solid white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            font-weight: bold;
            color: white;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
        }

        /* 姓名标签样式 */
        .name-label {
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            white-space: nowrap;
            margin-top: 2px;
            text-align: center;
        }

        /* 折叠按钮 */
        .sidebar-toggle {
            width: 100%;
            height: 28px;
            background-color: rgba(248, 249, 250, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.2s;
            margin-bottom: 8px;
            font-size: 12px;
            color: #666;
        }
        .sidebar-toggle:hover {
            background-color: rgba(33, 150, 243, 0.1);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .sidebar-toggle::before {
            content: '👥';
            font-size: 16px;
        }
        .sidebar.collapsed {
            transform: translateX(-100%);
            opacity: 0;
            pointer-events: none;
        }

        /* 显示按钮 - 当侧边栏隐藏时显示 */
        .show-sidebar-btn {
            position: absolute;
            top: 15px;
            left: 5px;
            width: 40px;
            height: 28px;
            background-color: rgba(248, 249, 250, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 4px;
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.2s;
            z-index: 1001;
            font-size: 16px;
            color: #666;
        }
        .show-sidebar-btn:hover {
            background-color: rgba(33, 150, 243, 0.1);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .show-sidebar-btn::before {
            content: '👥';
        }
        .sidebar.collapsed + .show-sidebar-btn {
            display: flex;
        }

        @media (max-width: 768px) {
            .content {
                height: calc(100vh - 85px);
                min-height: 350px;
            }
            .sidebar {
                width: 100px;
                max-width: 320px;
                max-height: 40%;
            }
            .sidebar h4 {
                font-size: 14px;
            }
            .show-all-btn {
                font-size: 11px;
                padding: 5px 6px;
            }
            .person-item {
                padding: 6px 10px;
                flex-direction: column;
                align-items: flex-start;
                gap: 2px;
            }
            .person-name {
                font-size: 13px;
            }
            .person-time {
                font-size: 10px;
            }
        }

        @media (max-width: 480px) {
            .content {
                height: calc(100vh - 85px);
                min-height: 300px;
            }
            .sidebar {
                top: 10px;
                left: 5px;
                width: 80px;
                max-height: calc(100vh - 80px);
                padding: 4px;
            }
            .show-sidebar-btn {
                top: 10px;
                left: 5px;
                width: 35px;
                height: 28px;
                font-size: 16px;
            }
            .room-input {
                gap: 8px;
            }
            .room-input input {
                font-size: 13px;
                padding: 6px 10px;
            }
            .room-input button {
                font-size: 13px;
                padding: 6px 12px;
            }
        }
    </style>
</head>
<body>
<div class="header">
    <div class="room-input">
        <input type="text" id="roomInput" placeholder="请输入房间名称" />
        <button id="searchBtn" onclick="searchRoom()">查询位置</button>
        <div class="auto-refresh-group">
            <button id="refresh10" class="refresh-btn" onclick="setAutoRefresh(10)">10秒</button>
            <button id="refresh20" class="refresh-btn" onclick="setAutoRefresh(20)">20秒</button>
            <button id="refresh30" class="refresh-btn" onclick="setAutoRefresh(30)">30秒</button>
            <button id="refreshStop" class="refresh-btn stop-btn" onclick="stopAutoRefresh()">停止</button>
        </div>
    </div>
    <div id="status">请输入房间名称查询位置信息</div>
    <div id="mapStatus" style="display: none;">
        <span id="mapStatusText"></span>
        <button id="retryMapBtn" onclick="retryMapLoad()" style="margin-left: 10px; padding: 4px 8px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;">重试地图</button>
    </div>
</div>

<div class="content">
    <div class="sidebar" id="sidebar">
        <div class="sidebar-toggle" id="sidebarToggle" onclick="toggleSidebar()"></div>
        <h4>成员列表 (<span id="personCount">0</span>)</h4>
        <button id="showAllBtn" class="show-all-btn" onclick="showAllUsers()" style="display: none;">
            🌍 显示全部
        </button>
        <ul id="personList" class="person-list">
            <li class="loading">暂无数据</li>
        </ul>
    </div>
    <div class="show-sidebar-btn" id="showSidebarBtn" onclick="toggleSidebar()"></div>
    <div id="map"></div>
</div>

<!-- Leaflet JavaScript -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
    // 初始化地图
    var map = L.map('map').setView([39.9042, 116.4074], 10);

    // 尝试多个瓦片服务以解决CORS问题
    function initializeTileLayer() {
        const tileServices = [
            // 使用国内镜像，通常没有CORS问题
            {
                url: 'https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                attribution: '© 高德地图',
                subdomains: '1234',
                maxZoom: 18
            },
            // OpenStreetMap 德国镜像 - 通常支持CORS
            {
                url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png',
                attribution: '© OpenStreetMap contributors',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            },
            // CartoDB 瓦片服务 - 支持CORS
            {
                url: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',
                attribution: '© CartoDB, © OpenStreetMap contributors',
                subdomains: 'abcd',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            },
            // Stamen 地图服务 - 支持CORS
            {
                url: 'https://stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png',
                attribution: '© Stamen Design, © OpenStreetMap contributors',
                subdomains: 'abcd',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            },
            // ESRI 世界地图 - 支持CORS
            {
                url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
                attribution: '© Esri, © OpenStreetMap contributors',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            },
            // 原始 OpenStreetMap - 作为最后备选
            {
                url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                attribution: '© OpenStreetMap contributors',
                maxZoom: 18,
                crossOrigin: 'anonymous'
            }
        ];

        let currentServiceIndex = 0;
        let currentTileLayer = null;

        function tryNextService() {
            if (currentServiceIndex >= tileServices.length) {
                console.error('所有瓦片服务都无法加载');
                const status = document.getElementById('status');
                status.textContent = '地图瓦片加载失败，可能是网络问题';
                status.className = 'error';
                return;
            }

            const service = tileServices[currentServiceIndex];
            console.log(`尝试瓦片服务 ${currentServiceIndex + 1}: ${service.url}`);

            // 移除之前的图层
            if (currentTileLayer) {
                map.removeLayer(currentTileLayer);
            }

            currentTileLayer = L.tileLayer(service.url, {
                attribution: service.attribution,
                maxZoom: service.maxZoom,
                subdomains: service.subdomains || 'abc',
                crossOrigin: service.crossOrigin || false,
                errorTileUrl: ''
            });

            let errorCount = 0;
            const maxErrors = 5; // 允许的最大错误数

            // 监听瓦片加载错误
            currentTileLayer.on('tileerror', function(error) {
                errorCount++;
                console.warn(`瓦片服务 ${currentServiceIndex + 1} 瓦片加载失败 (${errorCount}/${maxErrors}):`, error);

                if (errorCount >= maxErrors) {
                    console.warn(`瓦片服务 ${currentServiceIndex + 1} 错误过多，尝试下一个服务`);
                    currentServiceIndex++;
                    setTimeout(tryNextService, 1000); // 延迟1秒后尝试下一个服务
                }
            });

            // 监听瓦片加载成功
            currentTileLayer.on('tileload', function() {
                console.log(`瓦片服务 ${currentServiceIndex + 1} 加载成功`);
            });

            currentTileLayer.addTo(map);
        }

        // 开始尝试第一个服务
        tryNextService();
    }

    // 初始化瓦片图层
    initializeTileLayer();

    // 将缩放控件移到右下角
    map.zoomControl.setPosition('bottomright');

        // 全局变量
    var markers = [];
    var locationData = [];
    var currentActiveItem = null;

    // Mock数据开关 - 默认关闭，使用真实API
    var useMockData = false;

    // API配置
    var API_BASE_URL = 'http://locationshare.wangt.cc/nosso/quickreport/get';

    // 自动刷新相关变量
    var autoRefreshInterval = null;
    var currentRefreshSeconds = 0;
    var countdownInterval = null;
    var remainingSeconds = 0;

    // 创建自定义图标
    function createCustomIcon(name, index) {
        // 预定义的颜色和表情组合
        const iconStyles = [
            { bg: '#FF6B6B', emoji: '😊' },
            { bg: '#4ECDC4', emoji: '🌟' },
            { bg: '#45B7D1', emoji: '🎯' },
            { bg: '#96CEB4', emoji: '🚀' },
            { bg: '#FFEAA7', emoji: '💎' },
            { bg: '#DDA0DD', emoji: '🎨' },
            { bg: '#98D8C8', emoji: '🎪' },
            { bg: '#F7DC6F', emoji: '🎭' },
            { bg: '#BB8FCE', emoji: '🎸' },
            { bg: '#85C1E9', emoji: '🎲' }
        ];

        // 根据索引选择样式，确保同一个人总是相同的图标
        const style = iconStyles[index % iconStyles.length];

        const iconHtml = `
            <div class="custom-marker" style="background-color: ${style.bg}">
                ${style.emoji}
            </div>
        `;

        return L.divIcon({
            html: iconHtml,
            className: 'custom-div-icon',
            iconSize: [30, 30],
            iconAnchor: [15, 15],
            popupAnchor: [0, -15]
        });
    }

    // 创建带姓名标签的图标
    function createNamedIcon(name, index) {
        const iconStyles = [
            { bg: '#FF6B6B', emoji: '😊' },
            { bg: '#4ECDC4', emoji: '🌟' },
            { bg: '#45B7D1', emoji: '🎯' },
            { bg: '#96CEB4', emoji: '🚀' },
            { bg: '#FFEAA7', emoji: '💎' },
            { bg: '#DDA0DD', emoji: '🎨' },
            { bg: '#98D8C8', emoji: '🎪' },
            { bg: '#F7DC6F', emoji: '🎭' },
            { bg: '#BB8FCE', emoji: '🎸' },
            { bg: '#85C1E9', emoji: '🎲' }
        ];

        const style = iconStyles[index % iconStyles.length];

        const iconHtml = `
            <div style="display: flex; flex-direction: column; align-items: center;">
                <div class="custom-marker" style="background-color: ${style.bg}">
                    ${style.emoji}
                </div>
                <div class="name-label">${name}</div>
            </div>
        `;

        return L.divIcon({
            html: iconHtml,
            className: 'custom-div-icon',
            iconSize: [60, 50],
            iconAnchor: [30, 25],
            popupAnchor: [0, -25]
        });
    }

    // 坐标转换函数：WGS84转GCJ02（GPS坐标转火星坐标）
    function wgs84ToGcj02(lng, lat) {
        const a = 6378245.0;
        const ee = 0.00669342162296594323;

        if (outOfChina(lng, lat)) {
            return [lng, lat];
        }

        let dLat = transformLat(lng - 105.0, lat - 35.0);
        let dLng = transformLng(lng - 105.0, lat - 35.0);
        const radLat = lat / 180.0 * Math.PI;
        let magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        const sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI);
        dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * Math.PI);
        const mgLat = lat + dLat;
        const mgLng = lng + dLng;
        return [mgLng, mgLat];
    }

    function transformLat(lng, lat) {
        let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * Math.PI) + 320 * Math.sin(lat * Math.PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    function transformLng(lng, lat) {
        let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * Math.PI) + 300.0 * Math.sin(lng / 30.0 * Math.PI)) * 2.0 / 3.0;
        return ret;
    }

    function outOfChina(lng, lat) {
        return (lng < 72.004 || lng > 137.8347) || (lat < 0.8293 || lat > 55.8271);
    }

    // 判断是否为最近位置（10分钟内）
    function isRecentLocation(timeString) {
        const now = new Date();
        const targetTime = new Date(timeString);
        const diffMs = now - targetTime;
        const diffMinutes = Math.floor(diffMs / (1000 * 60));

        return diffMinutes <= 10; // 10分钟内认为是最近位置
    }

    // 格式化时间为相对时间
    function formatRelativeTime(timeString) {
        const now = new Date();
        const targetTime = new Date(timeString);
        const diffMs = now - targetTime;
        const diffMinutes = Math.floor(diffMs / (1000 * 60));
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffMinutes < 1) {
            const diffSeconds = Math.floor(diffMs / 1000);
            return `${diffSeconds}秒前`;
        } else if (diffMinutes < 2) {
            return '最近1分钟';
        } else if (diffMinutes < 3) {
            return '最近2分钟';
        } else if (diffMinutes < 4) {
            return '最近3分钟';
        } else if (diffMinutes < 5) {
            return '最近4分钟';
        } else if (diffMinutes < 10) {
            return '最近5分钟';
        } else if (diffMinutes < 30) {
            return `${diffMinutes}分钟前`;
        } else if (diffHours < 1) {
            return '半小时前';
        } else if (diffHours < 2) {
            return '1小时前';
        } else if (diffHours < 24) {
            return `${diffHours}小时前`;
        } else if (diffDays < 7) {
            return `${diffDays}天前`;
        } else {
            // 超过一周显示原始时间
            return timeString;
        }
    }

    // 搜索房间位置信息
    async function searchRoom() {
        const roomInput = document.getElementById('roomInput');
        const searchBtn = document.getElementById('searchBtn');
        const status = document.getElementById('status');

        const room = roomInput.value.trim();
        if (!room) {
            status.textContent = '请输入房间名称';
            status.className = 'error';
            return;
        }

        // 设置加载状态
        searchBtn.disabled = true;
        searchBtn.textContent = '查询中...';
        status.textContent = '正在查询位置信息...';
        status.className = '';

        try {
            let result;

            // 保存搜索历史
            saveSearchHistory(room);

            if (useMockData) {
                // 使用Mock数据
                console.log('使用Mock数据模式');

                // 模拟API延迟
                await new Promise(resolve => setTimeout(resolve, 800));

                // 模拟API返回数据
                const mockResult = {
                    "msg": "操作成功",
                    "code": 0,
                    "data": [
                        {
                            "id": 582,
                            "room": "love",
                            "name": "wt",
                            "longitude": 116.48240845,
                            "latitude": 40.00744558,
                            "ctime": "2025-09-24 19:12:00"
                        },
                        {
                            "id": 583,
                            "room": "love",
                            "name": "wangting",
                            "longitude": 116.58240845,
                            "latitude": 40.03744558,
                            "ctime": "2025-09-24 19:12:00"
                        },
                        {
                            "id": 543,
                            "room": "love",
                            "name": "wangting1",
                            "longitude": 115.58240845,
                            "latitude": 41.03744558,
                            "ctime": "2025-09-24 19:12:00"
                        },
                        {
                            "id": 513,
                            "room": "love",
                            "name": "wangting21",
                            "longitude": 112.58240845,
                            "latitude": 41.03744558,
                            "ctime": "2025-09-24 19:12:00"
                        }
                    ]
                };

                // 根据房间名称过滤数据
                result = mockResult;
                if (room.toLowerCase() !== 'love') {
                    // 如果不是love房间，返回空数据
                    result = {
                        "msg": "未找到该房间的位置信息",
                        "code": 0,
                        "data": []
                    };
                }
            } else {
                // 使用真实API
                console.log('使用真实API模式，请求URL:', `${API_BASE_URL}?room=${encodeURIComponent(room)}`);

                const response = await fetch(`${API_BASE_URL}?room=${encodeURIComponent(room)}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    // 添加超时处理
                    signal: AbortSignal.timeout(10000) // 10秒超时
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                result = await response.json();
                console.log('API返回数据:', result);
            }

            // 处理返回结果
            if (result.code === 0 && result.data && result.data.length > 0) {
                locationData = result.data;
                updatePersonList();
                updateMap();
                status.textContent = `成功获取 ${result.data.length} 个位置信息`;
                status.className = 'success';

                // 3秒后自动清除成功提示
                setTimeout(() => {
                    status.textContent = '';
                    status.className = '';
                }, 3000);
            } else {
                status.textContent = result.msg || '未找到位置信息';
                status.className = 'error';
                clearData();

                // 3秒后自动清除错误提示
                setTimeout(() => {
                    status.textContent = '';
                    status.className = '';
                }, 3000);
            }
        } catch (error) {
            console.error('API调用失败:', error);

            // 根据错误类型显示不同的错误信息
            if (error.name === 'TimeoutError') {
                status.textContent = '请求超时，请检查网络连接';
            } else if (error.name === 'TypeError' && error.message.includes('fetch')) {
                status.textContent = '网络连接失败，请检查网络状态';
            } else {
                status.textContent = `请求失败: ${error.message}`;
            }

            status.className = 'error';
            clearData();

            // 3秒后自动清除错误提示
            setTimeout(() => {
                status.textContent = '';
                status.className = '';
            }, 3000);
        } finally {
            searchBtn.disabled = false;
            searchBtn.textContent = '查询位置';
        }
    }

    // 更新人员列表
    function updatePersonList() {
        const personList = document.getElementById('personList');
        const personCount = document.getElementById('personCount');
        const showAllBtn = document.getElementById('showAllBtn');

        personCount.textContent = locationData.length;

        if (locationData.length === 0) {
            personList.innerHTML = '<li class="loading">暂无数据</li>';
            showAllBtn.style.display = 'none';
            return;
        }

        // 显示"显示全部"按钮
        showAllBtn.style.display = 'block';

        personList.innerHTML = '';
        locationData.forEach((person, index) => {
            const li = document.createElement('li');
            li.className = 'person-item';

            // 检查是否为最近位置，添加相应样式
            if (isRecentLocation(person.ctime)) {
                li.classList.add('recent');
            }

            li.setAttribute('data-index', index);
            li.innerHTML = `
                <div class="person-name">${person.name}</div>
                <div class="person-time">${formatRelativeTime(person.ctime)}</div>
            `;

            // 添加点击事件
            li.addEventListener('click', function() {
                selectPerson(index);
            });

            personList.appendChild(li);
        });
    }

    // 更新地图标记
    function updateMap(showNames = true) {
        // 清除现有标记
        markers.forEach(marker => map.removeLayer(marker));
        markers = [];

        if (locationData.length === 0) return;

        // 添加新标记
        locationData.forEach((person, index) => {
            // 根据是否显示姓名选择不同的图标
            const icon = showNames ? createNamedIcon(person.name, index) : createCustomIcon(person.name, index);

            // 坐标转换：将WGS84坐标转换为GCJ02坐标（适配高德地图）
            const [convertedLng, convertedLat] = wgs84ToGcj02(person.longitude, person.latitude);

            const marker = L.marker([convertedLat, convertedLng], { icon: icon })
                .addTo(map)
                .bindPopup(`
                    <b>${person.name}</b><br>
                    时间: ${person.ctime}
                `);

            // 添加标记点击事件
            marker.on('click', function() {
                selectPerson(index);
            });

            markers.push(marker);
        });

        // 自动缩放地图以显示所有标记点
        if (markers.length > 0) {
            const group = new L.featureGroup(markers);
            map.fitBounds(group.getBounds().pad(0.1));
        }
    }

    // 选择人员
    function selectPerson(index) {
        // 更新列表选中状态
        const personItems = document.querySelectorAll('.person-item');
        personItems.forEach(item => item.classList.remove('active'));

        if (personItems[index]) {
            personItems[index].classList.add('active');
        }

        // 地图定位到选中的人员
        const person = locationData[index];
        if (person) {
            // 坐标转换：将WGS84坐标转换为GCJ02坐标
            const [convertedLng, convertedLat] = wgs84ToGcj02(person.longitude, person.latitude);
            map.setView([convertedLat, convertedLng], 15);

            // 打开对应的弹窗
            if (markers[index]) {
                markers[index].openPopup();
            }
        }

        currentActiveItem = index;
    }

    // 显示全部用户
    function showAllUsers() {
        if (locationData.length === 0) return;

        // 清除所有人员的选中状态
        const personItems = document.querySelectorAll('.person-item');
        personItems.forEach(item => item.classList.remove('active'));

        // 重置当前活动项
        currentActiveItem = null;

        // 关闭所有弹窗
        markers.forEach(marker => marker.closePopup());

        // 自动缩放地图以显示所有标记点
        if (markers.length > 0) {
            const group = new L.featureGroup(markers);
            map.fitBounds(group.getBounds().pad(0.1));
        }

        console.log('已返回显示全部用户视图');
    }

    // 清除数据
    function clearData() {
        locationData = [];
        markers.forEach(marker => map.removeLayer(marker));
        markers = [];
        updatePersonList();
    }

    // 搜索历史管理
    const SEARCH_HISTORY_KEY = 'quickreport_search_history';
    const MAX_HISTORY_ITEMS = 10;

    // 加载搜索历史
    function loadSearchHistory() {
        try {
            const history = localStorage.getItem(SEARCH_HISTORY_KEY);
            return history ? JSON.parse(history) : [];
        } catch (e) {
            console.warn('读取搜索历史失败:', e);
            return [];
        }
    }

    // 保存搜索历史
    function saveSearchHistory(searchTerm) {
        if (!searchTerm || searchTerm.trim() === '') return;

        try {
            let history = loadSearchHistory();
            const term = searchTerm.trim();

            // 移除已存在的相同项
            history = history.filter(item => item !== term);

            // 添加到开头
            history.unshift(term);

            // 限制历史记录数量
            if (history.length > MAX_HISTORY_ITEMS) {
                history = history.slice(0, MAX_HISTORY_ITEMS);
            }

            localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history));
        } catch (e) {
            console.warn('保存搜索历史失败:', e);
        }
    }

    // 显示搜索建议
    function showSearchSuggestions(inputElement) {
        const history = loadSearchHistory();
        if (history.length === 0) return;

        // 移除现有的建议列表
        const existingSuggestions = document.querySelector('.search-suggestions');
        if (existingSuggestions) {
            existingSuggestions.remove();
        }

        // 创建建议列表
        const suggestions = document.createElement('div');
        suggestions.className = 'search-suggestions';
        suggestions.style.cssText = `
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-top: none;
            border-radius: 0 0 4px 4px;
            max-height: 150px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        `;

        // 添加建议项
        history.forEach(term => {
            const item = document.createElement('div');
            item.className = 'suggestion-item';
            item.textContent = term;
            item.style.cssText = `
                padding: 8px 12px;
                cursor: pointer;
                font-size: 14px;
                border-bottom: 1px solid #f0f0f0;
                transition: background-color 0.2s;
            `;

            item.addEventListener('mouseenter', function() {
                this.style.backgroundColor = '#f8f9fa';
            });

            item.addEventListener('mouseleave', function() {
                this.style.backgroundColor = 'white';
            });

            item.addEventListener('click', function() {
                inputElement.value = term;
                suggestions.remove();
                searchRoom();
            });

            suggestions.appendChild(item);
        });

        // 添加到输入框的父元素
        const parent = inputElement.parentElement;
        parent.style.position = 'relative';
        parent.appendChild(suggestions);

        // 点击其他地方关闭建议
        setTimeout(() => {
            document.addEventListener('click', function closeSuggestions(e) {
                if (!suggestions.contains(e.target) && e.target !== inputElement) {
                    suggestions.remove();
                    document.removeEventListener('click', closeSuggestions);
                }
            });
        }, 100);
    }

    // 初始化搜索输入框
    function initSearchInput() {
        const roomInput = document.getElementById('roomInput');

        // 输入框获得焦点时显示建议
        roomInput.addEventListener('focus', function() {
            if (this.value.trim() === '') {
                showSearchSuggestions(this);
            }
        });

        // 输入内容时更新建议
        roomInput.addEventListener('input', function() {
            if (this.value.trim() === '') {
                showSearchSuggestions(this);
            } else {
                // 移除现有的建议列表
                const existingSuggestions = document.querySelector('.search-suggestions');
                if (existingSuggestions) {
                    existingSuggestions.remove();
                }
            }
        });

        // 回车键搜索
        roomInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                // 移除建议列表
                const suggestions = document.querySelector('.search-suggestions');
                if (suggestions) {
                    suggestions.remove();
                }
                searchRoom();
            }
        });

        // 搜索按钮点击事件
        const searchBtn = document.getElementById('searchBtn');
        searchBtn.addEventListener('click', function() {
            // 移除建议列表
            const suggestions = document.querySelector('.search-suggestions');
            if (suggestions) {
                suggestions.remove();
            }
        });
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        initSearchInput();
        // 页面加载时自动填充最近的搜索词
        autoFillLastSearch();
    });

    // 自动填充最近的搜索词
    function autoFillLastSearch() {
        try {
            const history = loadSearchHistory();
            if (history && history.length > 0) {
                const roomInput = document.getElementById('roomInput');
                roomInput.value = history[0];
            }
        } catch (e) {
            console.warn('自动填充最近搜索词失败:', e);
        }
    }

    // 切换侧边栏显示/隐藏
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        sidebar.classList.toggle('collapsed');
    }

    // 重试地图加载
    function retryMapLoad() {
        console.log('重试加载地图瓦片...');
        const mapStatus = document.getElementById('mapStatus');
        mapStatus.style.display = 'none';

        // 重新初始化瓦片图层
        initializeTileLayer();
    }

    // 可选：添加点击事件获取坐标（调试用）
    map.on('click', function(e) {
        console.log('点击坐标: ' + e.latlng.lat + ', ' + e.latlng.lng);
    });

    // 监听视口变化，防止地址栏隐藏时布局错乱
    function handleViewportChange() {
        // 强制重新计算地图大小
        setTimeout(() => {
            if (map) {
                map.invalidateSize();
            }
        }, 100);
    }

    // 监听视口大小变化
    window.addEventListener('resize', handleViewportChange);

    // 监听方向变化
    window.addEventListener('orientationchange', () => {
        setTimeout(handleViewportChange, 500);
    });

    // 监听页面可见性变化（地址栏显示/隐藏时触发）
    document.addEventListener('visibilitychange', handleViewportChange);

    // 设置自动刷新
    function setAutoRefresh(seconds) {
        const roomInput = document.getElementById('roomInput');
        const room = roomInput.value.trim();

        if (!room) {
            alert('请先输入房间名称再设置自动刷新');
            return;
        }

        // 停止之前的自动刷新
        stopAutoRefresh();

        // 设置新的自动刷新
        currentRefreshSeconds = seconds;
        remainingSeconds = seconds;

        // 设置自动刷新定时器
        autoRefreshInterval = setInterval(() => {
            console.log(`自动刷新: ${seconds}秒间隔`);
            searchRoom();
            remainingSeconds = seconds; // 重置倒计时
        }, seconds * 1000);

        // 设置倒计时定时器
        countdownInterval = setInterval(() => {
            remainingSeconds--;
            updateCountdownDisplay();

            if (remainingSeconds <= 0) {
                remainingSeconds = seconds; // 重置倒计时
            }
        }, 1000);

        // 更新按钮状态
        updateRefreshButtonState(seconds);
        updateCountdownDisplay();

        console.log(`已设置${seconds}秒自动刷新`);
    }

    // 停止自动刷新
    function stopAutoRefresh() {
        if (autoRefreshInterval) {
            clearInterval(autoRefreshInterval);
            autoRefreshInterval = null;
            currentRefreshSeconds = 0;
        }

        if (countdownInterval) {
            clearInterval(countdownInterval);
            countdownInterval = null;
            remainingSeconds = 0;
        }

        // 重置所有按钮状态
        updateRefreshButtonState(0);
        updateCountdownDisplay();

        console.log('已停止自动刷新');
    }

    // 更新刷新按钮状态
    function updateRefreshButtonState(activeSeconds) {
        const buttons = document.querySelectorAll('.refresh-btn');
        buttons.forEach(btn => {
            btn.classList.remove('active');
        });

        if (activeSeconds > 0) {
            const activeBtn = document.getElementById(`refresh${activeSeconds}`);
            if (activeBtn) {
                activeBtn.classList.add('active');
            }
        }
    }

    // 更新倒计时显示
    function updateCountdownDisplay() {
        if (currentRefreshSeconds > 0 && remainingSeconds > 0) {
            const activeBtn = document.getElementById(`refresh${currentRefreshSeconds}`);
            if (activeBtn) {
                activeBtn.textContent = `${currentRefreshSeconds}秒 (${remainingSeconds})`;
            }
        } else {
            // 重置按钮文本
            const btn10 = document.getElementById('refresh10');
            const btn20 = document.getElementById('refresh20');
            const btn30 = document.getElementById('refresh30');

            if (btn10) btn10.textContent = '10秒';
            if (btn20) btn20.textContent = '20秒';
            if (btn30) btn30.textContent = '30秒';
        }
    }
</script>
</body>
</html>
